package com.JZ.QM.controller;

import com.JZ.QM.common.dao.WealthPositionDao;
import com.JZ.QM.common.entity.EntrustRecordEntity;
import com.JZ.QM.common.entity.WealthPositionEntity;
import com.JZ.QM.common.utils.CommonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.activation.CommandMap;
import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author lyp
 * @email lyp@gmail.com
 * @date 2020/7/5 12:08
 */

@RestController
@RefreshScope
@Slf4j
@RequestMapping(value="/fund")
public class FundEntrustController {

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    RabbitAdmin rabbitAdmin;
    @Resource
    WealthPositionDao wealthPositionDao;

    /**
     * 处理购买委托
     */
    @RequestMapping("/handleFundEntrust")
    public void handleFundEntrust() {
        //基金委托数量
        int numEntrust = 0;
        //建仓flag
        int saveWealthPositionFlag = 1;
        //回传消息列表
        ArrayList<Long> ackList = new ArrayList<>();

        numEntrust = getMessageCount("fundQueue");

        for (int i = 0; i <numEntrust ; i++) {
            //从消息队列中获取消息
            EntrustRecordEntity entrustRecordEntity = (EntrustRecordEntity) rabbitTemplate.receiveAndConvert("fundQueue");

            if(entrustRecordEntity != null){
                //财富持仓实体类
                WealthPositionEntity wealthPositionEntity = new WealthPositionEntity();
                //符合条件的数量
                int num = 0;
                //保存flag
                int saveFlag = 0;

                //构造条件查询器
                QueryWrapper<WealthPositionEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("pro_id",entrustRecordEntity.getProId())
                        .eq("wealth_account_id",entrustRecordEntity.getWealthAccountId());
                num = wealthPositionDao.selectCount(queryWrapper);

                //第一次持有，新建仓位
                if(num == 0){
                    wealthPositionEntity.setPositionAmount(entrustRecordEntity.getEntrustAmount());
                    wealthPositionEntity.setPositionShare(entrustRecordEntity.getEntrustShare());
                    wealthPositionEntity.setProId(entrustRecordEntity.getProId());
                    wealthPositionEntity.setUserId(entrustRecordEntity.getUserId());
                    wealthPositionEntity.setWealthAccountId(entrustRecordEntity.getWealthAccountId());
                    wealthPositionEntity.setIsUsed(1);

                    saveFlag = wealthPositionDao.insert(wealthPositionEntity);

                    //加仓操作
                }else {
                    wealthPositionEntity = wealthPositionDao.selectOne(queryWrapper);

                    wealthPositionEntity.setPositionAmount(wealthPositionEntity.getPositionAmount().add(entrustRecordEntity.getEntrustAmount()));
                    wealthPositionEntity.setPositionShare( wealthPositionEntity.getPositionShare() + entrustRecordEntity.getEntrustShare() );
                    wealthPositionEntity.setIsUsed(1);

                    saveFlag = wealthPositionDao.updateById(wealthPositionEntity);
                }

                if(saveFlag == 1){
                    ackList.add(entrustRecordEntity.getEntrustId());
                }
                saveWealthPositionFlag &= saveFlag;
            }
        }

        if(saveWealthPositionFlag == 1){
            //发送回传消息
            for (int i = 0; i <ackList.size() ; i++) {
                rabbitTemplate.convertAndSend("myExchange","ackFund",ackList.get(i));
            }
            log.info("委托处理完成");
        }else {
            log.info("委托处理失败");
        }
    }


    /**
     * 处理赎回委托
     * @return
     */
    @RequestMapping("/handleFundRedemptionEntrust")
    public CommonResult handleFundRedemptionEntrust(){
        //基金委托数量
        int numEntrust = 0;
        //建仓flag
        int saveWealthPositionFlag = 1;
        //回传消息列表
        ArrayList<Long> ackList = new ArrayList<>();

        numEntrust = getMessageCount("fundRedemptionQueue");

        for (int i = 0; i <numEntrust ; i++) {
            //从消息队列中获取消息
            EntrustRecordEntity entrustRecordEntity = (EntrustRecordEntity) rabbitTemplate.receiveAndConvert("fundRedemptionQueue");

            if(entrustRecordEntity != null){
                //财富持仓实体类
                WealthPositionEntity wealthPositionEntity = new WealthPositionEntity();
                //更新flag
                int updateFlag = 0;

                //构造条件查询器
                QueryWrapper<WealthPositionEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("pro_id",entrustRecordEntity.getProId())
                        .eq("wealth_account_id",entrustRecordEntity.getWealthAccountId());
                wealthPositionEntity = wealthPositionDao.selectOne(queryWrapper);

                if((wealthPositionEntity.getPositionShare()-entrustRecordEntity.getEntrustShare() ) == 0){
                    wealthPositionEntity.setIsUsed(0);
                }

                wealthPositionEntity.setPositionAmount(wealthPositionEntity.getPositionAmount().subtract(entrustRecordEntity.getEntrustAmount()));
                wealthPositionEntity.setPositionShare(wealthPositionEntity.getPositionShare() - entrustRecordEntity.getEntrustShare());

                updateFlag = wealthPositionDao.updateById(wealthPositionEntity);

                if(updateFlag == 1){
                    ackList.add(entrustRecordEntity.getEntrustId());
                }
                saveWealthPositionFlag &= updateFlag;
            }
        }

        if(saveWealthPositionFlag == 1){
            //发送回传消息
            for (int i = 0; i <ackList.size() ; i++) {
                rabbitTemplate.convertAndSend("myExchange","ackFundRedemption",ackList.get(i));
            }
            log.info("委托处理完成");
        }else {
            log.info("委托处理失败");
        }

        return CommonResult.success();
    }

    /**
     * 处理基金调仓委托
     * @return
     */
    @RequestMapping("/handleFundAdjustmentEntrust")
    public CommonResult handleFundAdjustmentEntrust(){
        //基金委托数量
        int numEntrust = 0;
        //更新仓位flag
        int updateWealthPositionFlag = 1;
        //回传消息列表
        ArrayList<Long> ackList = new ArrayList<>();

        numEntrust = getMessageCount("fundAdjustQueue");

        for (int i = 0; i <numEntrust ; i++) {
            //从消息队列中获取消息
            EntrustRecordEntity entrustRecordEntity = (EntrustRecordEntity) rabbitTemplate.receiveAndConvert("fundAdjustQueue");

            if(entrustRecordEntity != null){
                //财富持仓实体类
                WealthPositionEntity wealthPositionEntity = new WealthPositionEntity();
                //更新flag
                int updateFlag = 0;
                //构造条件查询器
                QueryWrapper<WealthPositionEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("pro_id",entrustRecordEntity.getProId())
                        .eq("wealth_account_id",entrustRecordEntity.getWealthAccountId())
                        .eq("user_id",entrustRecordEntity.getUserId());
                wealthPositionEntity = wealthPositionDao.selectOne(queryWrapper);

                log.info(String.valueOf(wealthPositionEntity));

                //卖出委托
                if(entrustRecordEntity.getEntrustType() == 1){
                    wealthPositionEntity.setPositionAmount(wealthPositionEntity.getPositionAmount().subtract(entrustRecordEntity.getEntrustAmount()));
                    wealthPositionEntity.setPositionShare(wealthPositionEntity.getPositionShare() - entrustRecordEntity.getEntrustShare());

                    if(wealthPositionEntity.getPositionShare() - entrustRecordEntity.getEntrustShare() == 0){
                        wealthPositionEntity.setIsUsed(0);
                    }

                    updateFlag = wealthPositionDao.updateById(wealthPositionEntity);

                    if(updateFlag == 1){
                        ackList.add(entrustRecordEntity.getEntrustId());
                    }
                    updateWealthPositionFlag &= updateFlag;

                    //买入委托
                }else {
                    wealthPositionEntity.setPositionAmount(wealthPositionEntity.getPositionAmount().add(entrustRecordEntity.getEntrustAmount()));
                    wealthPositionEntity.setPositionShare(wealthPositionEntity.getPositionShare() + entrustRecordEntity.getEntrustShare());

                    updateFlag = wealthPositionDao.updateById(wealthPositionEntity);

                    if(updateFlag == 1){
                        ackList.add(entrustRecordEntity.getEntrustId());
                    }
                    updateWealthPositionFlag &= updateFlag;
                }
            }
        }

        if(updateWealthPositionFlag == 1){
            //发送回传消息
            for (int i = 0; i <ackList.size() ; i++) {
                rabbitTemplate.convertAndSend("myExchange","ackFundAdjustment",ackList.get(i));
            }
            log.info("委托处理完成");
        }else {
            log.info("委托处理失败");
        }

        return CommonResult.success();
    }




    public int getMessageCount(String queue) {
        AMQP.Queue.DeclareOk declareOk = rabbitAdmin.getRabbitTemplate().execute(new ChannelCallback<AMQP.Queue.DeclareOk>() {
            public AMQP.Queue.DeclareOk doInRabbit(Channel channel) throws Exception {
                return channel.queueDeclarePassive(queue);
            }
        });
        return declareOk.getMessageCount();
    }
}
